package com.agile.leetcode.redis.redisson.lock;

import com.agile.leetcode.redis.redisson.config.RedissionConfig;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * 测试一
 *
 * @Author KD
 * @Date 2021/1/22 13:40
 */
public class LockAndUnLock {
    public static void main(String[] args) {
        LockAndUnLock lockAndUnLock=new LockAndUnLock();
        lockAndUnLock.test();
    }

    public void test() {
        // 定义锁
        String resourceName = "resource:x";
        // 拿到锁
        RedissonClient redissonClient = RedissionConfig.getRedissonClient();
        RLock lock = redissonClient.getLock(resourceName);
        // 多线程去获取锁
        new Thread(() -> {
            try {
                // 获取锁
                lock.lock();
                handler();
            } finally {
                System.out.println(Thread.currentThread().getName()+"释放锁了");
                // 释放锁
                lock.unlock();
            }
        }).start();
        // 多线程去获取锁
        new Thread(() -> {
            try {
                // 获取锁
                lock.lock();
                handler();
            } finally {
                System.out.println(Thread.currentThread().getName()+"释放锁了");
                // 释放锁
                lock.unlock();
            }
        }).start();
        System.out.println("主线程结束了==========");
    }

    /**
     * 具体业务执行
     */
    public void handler() {
        // 拿到线程名称
        System.out.println(Thread.currentThread().getName() + "获取到锁了");
        // 线程休眠
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
